#coding=utf-8
#本地http服务器
#
from gevent.pywsgi import WSGIServer
from gevent import monkey
import flask
from flask import render_template,url_for,request,json,redirect,session
from flask import jsonify
import pymysql
from interfaceData import req
import redis
import os
import datetime



monkey.patch_all()
app = flask.Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

#登录页渲染
@app.route('/',methods=["GET"])
def index():
    return render_template('login.html')

#主页渲染
@app.route('/main',methods=["GET"])
def main():
    return render_template('main.html')

#匿名登录
@app.route('/anonymous')
def anonymous_Login():
    user_ip = request.remote_addr #获取用户ip
    session["ip"] = user_ip  #设置匿名用户的ip地址为session
    main_url = url_for('main')
    return redirect(main_url)  #重定向到主页

#用户登录
@app.route('/user',methods=["POST"])
def user_Login():
    username = (request.form['username']).strip()
    pwd = (request.form['pwd']).strip()
    session["username"] = username
    try:
        cur.execute('select `passwd`,`endTime` from userAccount where `accountNumber` ="{0}";'.format(username))
        data=cur.fetchall()
        # print(data)
        # print(data[0][0])
        # print(data[0][1])
        if pwd == data[0][0] and datetime.datetime.now()<=data[0][1]:  #验证成功
            return jsonify({"state": "success", "code": 1})
        elif pwd == data[0][0] and datetime.datetime.now()>=data[0][1]:  #用户过期
            cur.execute('delete from userAccount where `accountNumber`="{0}";'.format(username)) #删除用户信息
            conn.commit()
            return jsonify({"state": "fail", "code": 2})
        else:  #密码验证错误
            return jsonify({"state": "fail", "code": 1})
    except Exception as e:  #用户名不存在
        # print(e)
        return jsonify({"state": "fail", "code": 0})



#主要逻辑
@app.route('/result',methods=["POST"])
def search():
    if request.method == "POST":
        server = (request.form['server']).strip()
        keyword = (request.form['keyword']).strip()
        #如果用户是匿名登录
        ip = session.get('ip')
        username = session.get('username')
        if ip:
            try:
                _=redis_clt2[ip]
                redis_clt2.incr(ip)
                if int(redis_clt2[ip]) >= 31:
                    return "tryover"
                else:
                    addks = server + keyword
                    # print(server)
                    # print(keyword)
                    usercookies = "7693E680FC4A30B72B6DAC426BEE0E1C9A8152837DD68CE42ACD1C384DAE6407D7BEB7E7714F81C13716A009EA9F3C98"

                    # 构造请求路径
                    # 获取大区密文
                    # 默认逐鹿
                    cur.execute("select sdata from server where `server`='{0}'".format(server))
                    server = cur.fetchall()[0][0]
                    # print(server)
                    # 获取商品密文
                    cur.execute("select gdata from goods where `goodsname`='{0}'".format(keyword))
                    try:
                        goodsname = cur.fetchall()[0][0]
                        # print(goodsname)
                        # 构造
                        psd = usercookies + server + goodsname

                        getpsd = redis_clt1.get(addks)

                        if getpsd == None:
                            resp = req(psd)  # 响应数据
                            # print(resp)

                            redis_clt1.set(addks, json.dumps(resp))  # 缓存
                            redis_clt1.expire(addks, 600)  # 缓存10分钟

                            shanghang = resp[0]  # 商行数据
                            tanwei = resp[1]  # 摊位数据
                            # li = []
                            # ui = []
                            # for i in shanghang.values():
                            #     li.append(i)
                            # for j in tanwei.values():
                            #     ui.append(j)
                            # print(resp)
                            return jsonify(shanghang, tanwei)

                        else:
                            resp = json.loads(getpsd.decode('utf-8'))
                            shanghang = resp[0]  # 商行数据
                            tanwei = resp[1]  # 摊位数据
                            return jsonify(shanghang, tanwei)
                    except:
                        return ""

            except:
                redis_clt2.set(ip, 1)
                redis_clt2.expire(ip, 86400)  # ip生存周期为24h
                # data = json.loads(request.form.get('data'))

                addks = server + keyword
                # print(server)
                # print(keyword)
                usercookies = "7693E680FC4A30B72B6DAC426BEE0E1C9A8152837DD68CE42ACD1C384DAE6407D7BEB7E7714F81C13716A009EA9F3C98"

                # 构造请求路径
                # 获取大区密文
                # 默认逐鹿
                cur.execute("select sdata from server where `server`='{0}'".format(server))
                server = cur.fetchall()[0][0]
                # print(server)
                # 获取商品密文
                cur.execute("select gdata from goods where `goodsname`='{0}'".format(keyword))
                try:
                    goodsname = cur.fetchall()[0][0]
                    # print(goodsname)
                    # 构造
                    psd = usercookies + server + goodsname

                    getpsd = redis_clt1.get(addks)

                    if getpsd == None:
                        resp = req(psd)  # 响应数据
                        # print(resp)
                        redis_clt1.set(addks, json.dumps(resp))  # 缓存
                        redis_clt1.expire(addks, 600)  # 缓存10分钟
                        shanghang = resp[0]  # 商行数据
                        tanwei = resp[1]  # 摊位数据
                        # li = []
                        # ui = []
                        # for i in shanghang.values():
                        #     li.append(i)
                        # for j in tanwei.values():
                        #     ui.append(j)
                        # print(resp)
                        return jsonify(shanghang, tanwei)

                    else:
                        resp = json.loads(getpsd.decode('utf-8'))
                        shanghang = resp[0]  # 商行数据
                        tanwei = resp[1]  # 摊位数据
                        return jsonify(shanghang, tanwei)
                except:
                    return ""

        elif username:
            addks = server + keyword
            # print(server)
            # print(keyword)
            usercookies = "7693E680FC4A30B72B6DAC426BEE0E1C9A8152837DD68CE42ACD1C384DAE6407D7BEB7E7714F81C13716A009EA9F3C98"

            # 构造请求路径
            # 获取大区密文
            # 默认逐鹿
            cur.execute("select sdata from server where `server`='{0}'".format(server))
            server = cur.fetchall()[0][0]
            # print(server)
            # 获取商品密文
            cur.execute("select gdata from goods where `goodsname`='{0}'".format(keyword))
            try:
                goodsname = cur.fetchall()[0][0]
                # print(goodsname)
                # 构造
                psd = usercookies + server + goodsname

                getpsd = redis_clt1.get(addks)

                if getpsd == None:
                    resp = req(psd)  # 响应数据
                    # print(resp)

                    redis_clt1.set(addks, json.dumps(resp))  # 缓存
                    redis_clt1.expire(addks, 600)  # 缓存10分钟

                    shanghang = resp[0]  # 商行数据
                    tanwei = resp[1]  # 摊位数据
                    # li = []
                    # ui = []
                    # for i in shanghang.values():
                    #     li.append(i)
                    # for j in tanwei.values():
                    #     ui.append(j)
                    # print(resp)
                    return jsonify(shanghang, tanwei)

                else:
                    resp = json.loads(getpsd.decode('utf-8'))
                    shanghang = resp[0]  # 商行数据
                    tanwei = resp[1]  # 摊位数据
                    return jsonify(shanghang, tanwei)
            except:
                return ""

    elif request.method == "GET":
        return render_template('requestError.html')

    # pass

def keyword_TTL(cli,resp):
    '''缓存搜索内容，生存周期为10分钟'''
    cli.rpush('data',resp)
    cli.expire('data',6000) #生存周期为6000
    return

#注册页渲染
@app.route('/register')
def register():
    return render_template('register.html')

@app.route('/registers',methods=["POST"])
def deal_register():
    username = (request.form['username']).strip()
    pwd = (request.form['pwd']).strip()
    kahao = (request.form['kahao']).strip()
    #判断用户名
    cur.execute('select * from userAccount where `accountNumber`="{0}";'.format(username))
    a=cur.fetchall()
    if len(a)>0:
        return jsonify({"state": "fail", "code": 1})  #用户名已经存在
    else:
        create = datetime.datetime.now()  #注册时间
        end = create+datetime.timedelta(days = 30)  #有效期30天
        if len(redis_clt3.lrange(kahao,0,0))>0:
            redis_clt3.rpop(kahao)  #删除卡号
            cur.execute('insert into userAccount(`accountNumber`,`passwd`,`createTime`,`endTime`)values {}'.format((username,pwd,create.strftime('%Y-%m-%d %H:%M:%S'),end.strftime('%Y-%m-%d %H:%M:%S'))))
            conn.commit()
            return jsonify({"state":"success","code":1})
        else:
            return jsonify({"state": "fail", "code": 0})

if __name__ == '__main__':
    # 用os模块来读取
    password="pwd"

    conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",password=password,db="QQSG",charset="utf8") #商品构造数据表
    cur = conn.cursor()

    redis_clt1 = redis.Redis(host='127.0.0.1',port = 6379,db=0,password = password) #db0存储psd
    redis_clt2 = redis.Redis(host = '127.0.0.1', port = 6379, db = 1, password = password)  # db0存储ip计数
    redis_clt3 = redis.Redis(host = '127.0.0.1', port = 6379, db = 2, password = password)  # 存储卡密

    WSGIServer(('0.0.0.0', 5000), app).serve_forever()